package conf2;

import conf2.model.Move;
import conf2.ui.PieceCollection;
import java.util.LinkedList;
import java.util.Queue;


public class Animator implements Animation.Listener {

    public static final int NSTEPS = 33;
    public static final int DELAY = 33;
    public static final int TIME = NSTEPS * DELAY;
    private boolean isPlaying = false;
    private final PieceCollection pieceColl;
    private final Queue<Animation> animationQueue = new LinkedList<Animation>();

    public Animator(PieceCollection pieceColl)
    {
        this.pieceColl = pieceColl;
    }


    public synchronized boolean isPlaying() {
        return isPlaying;
    }

    private synchronized void setPlaying(boolean b) {
        isPlaying = b;
    }

    public void queueAnimation(final Move move, final Animation.Listener listener) {
        Animation anim = new Animation(pieceColl, move);
        anim.addAnimationListener(this);
        anim.addAnimationListener(listener);
        synchronized (animationQueue) {
            animationQueue.add(anim);
        }
    }

    public void start() {
        if (!isPlaying()) {
            Animation anim;
            synchronized (animationQueue) {
                anim = animationQueue.poll();
            }
            setPlaying(true);
            anim.execute();
        }
    }

    public void animationFinished() {
        synchronized (animationQueue) {
            if (animationQueue.isEmpty()) {
                setPlaying(false);
            } else {
                Animation anim = animationQueue.poll();
                anim.execute();
            }
        }
    }
}
